// tslint:disable
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController, Platform } from '@ionic/angular';
import { JPush } from '@jiguang-ionic/jpush/ngx';
import { IndexedDBService } from 'src/app/shared/service/indexed-db.service';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { PageModalService } from '../../shared/service/page-modal-service';

declare var Fingerprint; // 1.7.0 指纹登录插件
declare var FingerprintAuth; // 1.7.0 安卓端打包兼容用

// TODO 我的 - 设置
@Component({
    selector: 'app-settings',
    templateUrl: 'settings.page.html',
    styleUrls: ['settings.page.scss']
})
export class SettingsPage implements OnInit {
    cacheSize: any = '0 B';
    targetObj: any; // 路由对象
    ifLogin: boolean;
    @Input() tagData: any = {};
    appTypeCustom = "";
    enableFingerPrint = false; // 只用于当前页面的存储
    isAvailableFingerPrint = true; // 默认支持指纹 // 项目预览环境 先给个true用于弹出指纹登录窗口


    personalized: any;
    personalized2: any;
    localAppVersion = '';
    effectTimeLabel = '';
    effectTimeLabelCssStyle = '';
    cautionFirstLabel = '';
    cautionBoxCssStyle = '';
    cautionFirstRowBoxCssStyle = '';
    cautionFirstLabelIcon = '';
    cautionFirstLabelIconCssStyle = '';
    cautionFirstLabelCssStyle = '';
    cautionSecondLabel1 = '';
    cautionSecondLabel1CssStyle = '';
    cautionSecondLabel2 = '';
    cautionSecondLabel2CssStyle = '';
    cautionSecondLabel3 = '';
    cautionSecondLabel3CssStyle = '';
    isShowButton = false; // 2023-10-17 是否在特定环境显示分享按钮
    constructor(
        public router: Router,
        private alert: AlertController,
        public eventService: EventService,
        public indexedDBService: IndexedDBService,
        private http: HttpService,
        public appGlobalService: AppGlobalService,
        private pageModalService: PageModalService,
        private platform: Platform,
        private jPush: JPush,
    ) {
    }

    ngOnInit() {
        // 2023.12.28 是否在特定环境显示微信登录按钮   线上项目预览,测试环境项目预览,apk 则显示按钮 其他情况如H5,不显示
        this.isShowButton = this.appGlobalService.checkIsPreviewAndIsApp();
        const bodyStyles = window.getComputedStyle(document.body);
        this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
        // console.log(this.tagData,'tagdataaa');

        this.ifLogin = localStorage.getItem('userId') !== null;
        if (this.tagData && this.tagData.data && this.tagData.data.length) {
            this.tagData.data.forEach(e => {
                if (e.tagStyle === 'exit') {
                    const params = {
                        content: {},
                        id: e.submit.id,
                        sessionId: localStorage.getItem('sessionId')
                    };
                    localStorage.setItem('logoutParams', JSON.stringify(params));
                } else if (e.tagStyle === 'fingerprint') { // 赚钱宝新增指纹登录 1.7.0
                    if (localStorage.getItem('client') !== 'BROWSER' && (this.platform.is('ios') || this.platform.is('android'))) {
                        if (localStorage.getItem('platform') === 'ios') {  // ios
                            if ((typeof Fingerprint) !== 'undefined') {
                                Fingerprint.isAvailable((successResult) => {
                                    console.log("isAvailable:", successResult);
                                    if (successResult && successResult === 'face') {
                                        this.isAvailableFingerPrint = false;
                                    } else {
                                        this.isAvailableFingerPrint = true;
                                    }
                                }, (errorResult) => {
                                    this.isAvailableFingerPrint = false;
                                    console.log('您的设备不支持指纹！');
                                }, {});
                            }
                        } else if (localStorage.getItem('platform') === 'android') { // android
                            if ((typeof FingerprintAuth) !== 'undefined') {
                                FingerprintAuth.isAvailable((successResult) => {
                                    if (successResult.isAvailable) {
                                        this.isAvailableFingerPrint = true;
                                    } else {
                                        this.isAvailableFingerPrint = false;
                                    }
                                }, (errorResult) => {
                                    // this.appGlobalService.showToast('您的设备不支持指纹！', 1500, 'bottom');
                                    this.isAvailableFingerPrint = false;
                                    console.log('您的设备不支持指纹！');
                                }, {});
                            }
                        } else { // 项目预览
                            this.isAvailableFingerPrint = false;
                        }
                    }
                    if (e.link !== undefined && e.link.param !== undefined) {
                        e.link.param.forEach(element => {
                            if (element.name === 'enableFingerPrint') {
                                if (localStorage.getItem('enableFingerPrint') !== null && (localStorage.getItem('enableFingerPrint') === '1' || localStorage.getItem('enableFingerPrint') === '2')) {
                                    this.enableFingerPrint = true;
                                } else {
                                    this.enableFingerPrint = false;
                                }
                            }
                        });
                    }
                } else if (e.tagStyle === 'aboutUs') { // 蜂喔用户新增关于我们显示真机版本号
                    if (localStorage.getItem('localAppVersion')) {
                        this.localAppVersion = localStorage.getItem('localAppVersion');
                    } else {
                        if (e.link !== undefined && e.link.param !== undefined) {
                            e.link.param.forEach(element => {
                                if (element.name === 'localAppVersion') {
                                    this.localAppVersion = element.value;
                                }
                            });
                        }
                    }
                } else if (e.tagStyle === 'clearCache') {
                    this.appGlobalService.getObjectStoreSize(res => {
                        this.cacheSize = res;
                    });
                } else if (e.tagStyle === 'logout') {
                    if (e.link !== undefined && e.link.param !== undefined) {
                        e.link.param.forEach(element => {
                            if (element.name === 'effectTimeLabel') {
                                this.effectTimeLabel = element.value;
                            } else if (element.name === 'effectTimeLabelCssStyle') {
                                this.effectTimeLabelCssStyle = element.value;
                            } else if (element.name === 'cautionFirstLabel') {
                                this.cautionFirstLabel = element.value;
                            } else if (element.name === 'cautionBoxCssStyle') {
                                this.cautionBoxCssStyle = element.value;
                            } else if (element.name === 'cautionFirstRowBoxCssStyle') {
                                this.cautionFirstRowBoxCssStyle = element.value;
                            } else if (element.name === 'cautionFirstLabelIcon') {
                                this.cautionFirstLabelIcon = element.value;
                            } else if (element.name === 'cautionFirstLabelIconCssStyle') {
                                this.cautionFirstLabelIconCssStyle = element.value;
                            } else if (element.name === 'cautionFirstLabelCssStyle') {
                                this.cautionFirstLabelCssStyle = element.value;
                            } else if (element.name === 'cautionSecondLabel1') {
                                this.cautionSecondLabel1 = element.value;
                            } else if (element.name === 'cautionSecondLabel1CssStyle') {
                                this.cautionSecondLabel1CssStyle = element.value;
                            } else if (element.name === 'cautionSecondLabel2') {
                                this.cautionSecondLabel2 = element.value;
                            } else if (element.name === 'cautionSecondLabel2CssStyle') {
                                this.cautionSecondLabel2CssStyle = element.value;
                            } else if (element.name === 'cautionSecondLabel3') {
                                this.cautionSecondLabel3 = element.value;
                            } else if (element.name === 'cautionSecondLabel3CssStyle') { this.cautionSecondLabel3CssStyle = element.value; }
                        });
                    }
                } else if (e.tagStyle === 'normalBtn') {
                    if (e.submit && e.submit.content.state === "1") {
                        this.personalized = true;
                    } else {
                        this.personalized = false;
                    }
                } else if (e.tagStyle === 'normalBtn2') {
                    if (e.submit && e.submit.content.state === "1") {
                        this.personalized2 = true;
                    } else {
                        this.personalized2 = false;
                    }
                }


            });
        }

    }


    dismiss() {
        this.appGlobalService.goBack();
    }
    clearCache() {
        if (this.cacheSize !== '0 B') {
            this.appGlobalService.clearALLCacheData('cache', res => {
                if (res != "-1") {
                    this.cacheSize = '0 B';
                }
            });
        }
        // 清除表单草稿
        const arr = Object.keys(localStorage)
        let arrKey = [];
        arr.forEach(element => {
            if(element.indexOf("saveDraft:") > -1) {
            arrKey.push(element); 
            }
        });
        if (arrKey.length){
            arrKey.forEach(element => {
            localStorage.removeItem(element)
            });
}

    }


    jumpToPage(obj) {
        const sessionId = localStorage.getItem('sessionId');
        // tslint:disable-next-line:prefer-const
        let linkParams = {};
        if (obj.link.param && obj.link.param[0]) {
            obj.link.param.forEach(element => {
                if (element.name.includes('parent_params_')) {
                    let filedName = element.name.replace('parent_params_', '');
                    obj.link[filedName] = element.value;
                } else {
                    linkParams[element.name] = element.value;
                    
                }
            });
        }
        obj.link['params']=linkParams;
        let pageParams = {
            pageId: obj.link.target,
            params: linkParams,
            type: obj.link.type,
            sessionId
        };
        if (!(obj.link.type && obj.link.type === "pageModal")) {
            pageParams = obj.link;
        }
        this.pageModalService.openPage(pageParams);
    }

    async logout(obj) {
        const that = this;
        const alert = await this.alert.create({
            message: '注销账号后账号相关服务内容将被清空，确定注销吗？',
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: () => {
                    }
                }, {
                    text: '确定',
                    cssClass: 'LJ',
                    handler: () => {
                        that.doLogoutAuto(obj, 'logout');
                    }
                }
            ]
        });
        await alert.present();
    }



    async doLogout(obj) {
        const that = this;
        const alert = await this.alert.create({
            message: '确定要退出当前账户？',
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: () => {
                    }
                }, {
                    text: '确定',
                    cssClass: 'LJ',
                    handler: () => {
                        that.doLogoutAuto(obj, 'exit');
                    }
                }
            ]
        });
        await alert.present();
    }
    async call(mobile) {
        let companyName = "铺铺旺 ";
        if (this.appTypeCustom === 'LJ') {
            companyName = "蜂喔 ";
        }
        const alert = await this.alert.create({
            header: this.tagData.data.nick_name,
            message: companyName + mobile,
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    cssClass: 'secondary'
                }, {
                    text: '拨打',
                    handler: () => {
                        this.http.changeCallNumber(mobile);
                    }
                }
            ]
        });
        await alert.present();
    }
    doLogoutAuto(o, type) {
        let obj: any;
        if (this.tagData && this.tagData.data && this.tagData.data.length) {
            if (type === 'logout') {
                this.tagData.data.forEach(e => {
                    if (e.tagStyle === 'logout') {
                        obj = e;
                    }
                });
            } else if (type === 'exit') {
                this.tagData.data.forEach(e => {
                    if (e.tagStyle === 'exit') {
                        obj = e;
                    }
                });
            }
        }
        this.initData(obj, o);
    }

    initData(obj, o) {
        const that = this;
        const params = {
            content: {},
            id: obj.submit.id,
            sessionId: localStorage.getItem('sessionId')
        };
        this.http.post('application/submit', params, res => {
            if (res.success) {
                // 2024.07.09 初始化临时全局变量
                that.appGlobalService.initTemporaryVariables();
                this.eventService.eventEmit.removeAllListeners("clearlistTagRefreshTime");
                // 不硬性删除unreadchat表
                // this.indexedDBService.clearTableData('unreadchat');
                localStorage.setItem('needRefreshTab1', 'true');
                localStorage.setItem('needRefreshTab2', 'true');
                localStorage.setItem('needRefreshTab3', 'true');
                localStorage.setItem('needRefreshTab4', 'true');
                localStorage.setItem('needRefreshTab5', 'true');
                this.appGlobalService.showToast(res.message, 1500, 'middle');
                localStorage.removeItem('userInfo');
                localStorage.removeItem('targetObj');
                localStorage.removeItem('loginStatus');
                this.appGlobalService.loginStatus = false;
                localStorage.removeItem('userInfo');
                localStorage.removeItem('tag.IconListLogic');
                localStorage.removeItem('tempPoint');
                localStorage.removeItem('loginParams');
                localStorage.removeItem('ALP');
                localStorage.removeItem('userId');
                localStorage.removeItem('connUserId');
                localStorage.setItem('onLogoutWebSocketTag', 'true');
                localStorage.removeItem('isDetailPage');
                localStorage.removeItem('invitationArr');
                localStorage.removeItem('inMsgNum');
                localStorage.removeItem('isEnterDetailChatPage');
                localStorage.removeItem('shareOppDetail');
                localStorage.removeItem('needRemberResult');
                localStorage.removeItem('refreshbtNavDefaultTabForPxwTag');
                localStorage.removeItem('dynamicScrollTop');
                localStorage.removeItem('backToNewShop');
                localStorage.removeItem('backgroundPauseTime');
                localStorage.removeItem('privacyStatement');
                localStorage.removeItem("titleBarBackCount");
                localStorage.removeItem('myrealEstateresetAssured');
                localStorage.removeItem('myrealEstatequickWay');
                localStorage.removeItem('myrealEstateOppId');
                localStorage.removeItem('quote_way');
                localStorage.removeItem('switchShopJumpPage');
                this.appGlobalService.resetMessageData();

                if (this.appGlobalService.clientType === 'pxw') {
                    // 铺小旺退出登录remove firstPostion
                    localStorage.removeItem('firstPostion');
                }
                // 1.7.0 新增指纹登录参数
                if (localStorage.getItem('enableFingerPrint') !== null && localStorage.getItem('enableFingerPrint') === '1') {
                    localStorage.setItem('enableFingerPrint', '2');
                }
                that.jPush.deleteAlias({ sequence: 1 }).then((result) => {
                    const sequence = result.sequence;
                    console.log('删除别名成功' + sequence);
                }, (error) => {
                    const sequence = error.sequence;
                    const errorCode = error.code;
                    console.log('删除别名失败：' + errorCode);
                });
                this.eventService.eventEmit.emit("onLogoutWebSocket", 'logout');
                // 铺小旺清除更新业绩等信息的定时器息
                if (this.appGlobalService.clientType === 'pxw') {
                    localStorage.setItem('clearAchieveInfoTimerTag', '1');
                    this.eventService.eventEmit.emit("clearAchieveInfoTimer");
                }


                setTimeout(() => {
                    if (this.appGlobalService.clientType === 'pxw' || this.appGlobalService.clientType === 'js') {
                        that.jumpToPage(obj);
                        that.clearCache();
                        localStorage.removeItem('tab1PartData'); // 清楚part1 接口数据           
                    } else {
                        if (o) {
                            // 手动退出
                            console.log("手动退出登录！");
                            // this.eventService.eventEmit.emit(localStorage.getItem('tab'), '1');
                            // this.router.navigate([localStorage.getItem('tabPath')]);
                            setTimeout(() => {
                                //刷新我的页面应该在导航到我的页面之后执行
                                this.appGlobalService.popTarget();
                                this.appGlobalService.goBack();
                                
                            }, 800);

                        } else {
                            // 自动退出登录
                            console.log("自动退出登录！");
                        }
                    }
                }, 0);



            } else {
                this.appGlobalService.showToast(res.message, 1500, 'middle');
            }
        });
    }


    // 指纹登录
    // TODO enableFingerPrint 为 -1 不校验指纹或者指纹校验失败
    // TODO enableFingerPrint 为 null  第一次弹窗
    // TODO enableFingerPrint 为 1  指纹验证通过 并且开启
    // TODO enableFingerPrint 为 2  已经开启过然后正常退出到首页第二次指纹登录时弹出
    switchToFingerPrintLogin(item) {
        console.log('...enableFingerPrint = ' + this.enableFingerPrint);
        // 2023.12.29 打开指纹开关
        if (this.enableFingerPrint) {
            if (item.link.param !== undefined) {
                let tempParams = {};
                item.link.param.forEach(element => {
                    tempParams[element.name] = element.value;
                });
                item.link['params'] = tempParams;
            }
            this.pageModalService.openPage(item.link, '', result => {
                if (result) {
                    if (result.success !== undefined && result.success === true) {
                        this.enableFingerPrint = true;
                        return;
                    } else if (result.success !== undefined && result.success === false) {
                        this.enableFingerPrint = false;
                        return;
                    }
                    if (localStorage.getItem('enableFingerPrint') !== null && localStorage.getItem('enableFingerPrint') === '1') {
                        this.enableFingerPrint = true;
                    }
                } else {
                    this.enableFingerPrint = false;
                }
            });
        } else {
            localStorage.setItem('enableFingerPrint', '-1');
        }
    }

    showBtn(item, type) {
        if (item.submit.content.state === '1') {
            item.submit.content.state = '0';
        } else {
            item.submit.content.state = '1';
        }
        const params = {
            content: item.submit.content,
            id: item.submit.id,
            sessionId: localStorage.getItem('sessionId')
        };
        this.http.post('application/submit', params, res => {
            if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, 'middle');
            }
        });
    }
}
